<?php
namespace App\Controllers\Coupons;


use App\Models\Coupon\Coupons;
use App\Libs\Views\Json;
/**
    修改或者添加代金券;
 */
class CreateAlterCoupons extends \App\Libs\Base\BaseAction
{

    public function execute()
    {
        $map = [
            'title'         =>'title',
            'full_price'    =>'full_price',
            'price'         =>'decre_price',
            'start_time'    =>'start_time',
            'end_time'      =>'end_time',
            'is_show'       =>'show',
            'integral'      =>'need_credit',
        ];
        if($this->request->isPost()){
            $couponID = $this->request->getPost('cid')??[];
            if(empty($couponID)){
                $matchCoupon = new Coupons();
                $matchCoupon->ctime = date('Y:m:d H:i:s');
                $matchCoupon->utime = date('Y:m:d H:i:s');
            }else{
                $matchCoupon = Coupons::findOne($couponID);
                $matchCoupon->utime = date('Y:m:d H:i:s');
            }
            $post = $this->request->getPost();
            foreach ($map as $key => $val){
                if(isset($post[$val])){
                    $matchCoupon->{$key} = $post[$val];
                }
            }
            if($matchCoupon->save()){
                return Json::view(0,'操作成功',[]);
            }else{
                return Json::view(1,'操作失败请重试',[]);
            }

        }else{
            if(!$this->request->hasQuery('cid')){
                return Json::view(1,'缺少参数：cid,券id',[]);
            }
            $couponID = $this->request->get('cid');
            $matchCoupon = Coupons::findOne($couponID);
            foreach ($map as $key => $val){
                if(isset($matchCoupon->{$key})){
                    $newData[$val] = $matchCoupon->{$key};
                }
            }
            $newData['id'] = $matchCoupon->id;
            return Json::view(0,'ok',$newData);
        }

    }
}
